
import { IState, MODELS, SUBJECTS } from "@/typings";
import React, {  FC, useMemo } from "react";

//useSelector 获取state 
//useDispatch 改变state
import { useSelector, useDispatch } from 'react-redux';
import { Dispatch } from 'redux';
import * as types from '../store/actionTypes';

import Header from '../components/Header';
import Subject from '../components/Subject';
import Model from '../components/Model';
import Button from '../components/Button';

const Home: FC = () => {
  const dispatch: Dispatch = useDispatch();

  //useSelector()可以拿到state里的数据
  const curSubject: SUBJECTS = useSelector((state: IState) => state.curSubject);
  const curModel: MODELS = useSelector((state: IState) => state.curModel);
  const modelShow: boolean = useSelector((state: IState) => state.modelShow);


  //缓存父组件的写法一： useCallback()
  //更改当前科目state数据
  // const setCurrentSubject: (subject: SUBJECTS) => void = useCallback((subject) => {
  //   dispatch({ type: types.SET_CURRENT_SUBJECT, payload: subject });
  // }, [dispatch]);

  //更改当前驾照类型state数据
  // const setCurrentModel: (model: MODELS) => void = useCallback((model) => {
  //   dispatch({ type: types.SET_CURRENT_MODEL, payload: model });
  // }, [dispatch]);

  //缓存父组件的写法二： useMemo()
  const [setCurrentSubject, setCurrentModel] = useMemo(() => {
    //可以返回一个数组里面包含多个向子组件传值的函数方法
    return [
      (subject:SUBJECTS) => dispatch({ type: types.SET_CURRENT_SUBJECT, payload: subject }),
      (model:MODELS) => dispatch({ type: types.SET_CURRENT_MODEL, payload: model })
    ]
   }, [dispatch]);

  return (
    <div className="container">
      <Header headerTitle="驾照考题" iconShow={false} />
      <Subject curSubject={curSubject} setCurrentSubject={setCurrentSubject} />
      <Model curModel={curModel} setCurrentModel={setCurrentModel} modelShow={modelShow} />
      <Button btnTitle="开始考试" path="/test" />
    </div>
  );
}

export default Home;